/**************************************************************************\
    Copyright Microsoft Corporation. All Rights Reserved.
\**************************************************************************/

namespace Conmigo.Widgets.TypeControls
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using Standard;
    using Microsoft.Win32;

    public partial class NameControl : UserControl
    {
        private static readonly Dictionary<string, string> _FileExtensionToImageMimeTypeMap = new Dictionary<string,string>
        {
            { "bmp",   "image/bmp"},
            { "cod",   "image/cis-cod"},
            { "gif",   "image/gif" },
            { "ief",   "image/ief" },
            { "jpg",   "image/jpeg" },
            { "jpe",   "image/jpeg" },
            { "jpeg",  "image/jpeg" },
            { "jfif",  "image/pipeg" },
            { "png",   "image/png" },
            { "svg",   "image/svg+xml" },
            { "tif",   "image/tiff" },
            { "tiff",  "image/tiff" },
            { "ras",   "image/x-cmu-raster" },
            { "cmx",   "image/x-cmx" },
            { "ico",   "image/x-icon" },
            { "pnm",   "image/x-portable-anymap" },
            { "pbm",   "image/x-portable-bitmap" },
            { "pgm",   "image/x-portable-graymap" },
            { "ppm",   "image/x-portable-pixmap" },
            { "rgb",   "image/x-rgb" },
            { "xbm",   "image/x-xbitmap" },
            { "xpm",   "image/x-xpixmap" },
            { "xwd",   "image/x-xwindowdump" },
        };

        private static string _TryGetExtensionFromMimeType(string mimeType)
        {
            // default to pretending that a file is a jpg.
            if (!string.IsNullOrEmpty(mimeType))
            {
                foreach (var pair in _FileExtensionToImageMimeTypeMap)
                {
                    if (mimeType.Equals(pair.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        return pair.Key;
                    }
                }
            }
            return "jpg";
        }

        private static string _TryGetMimeTypeFromExtension(string fileName)
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                string ext = Path.GetExtension(fileName);
                // Usually the case.
                if (ext.StartsWith(".", StringComparison.Ordinal))
                {
                    ext = ext.Substring(1);
                }

                string mimeType;
                if (_FileExtensionToImageMimeTypeMap.TryGetValue(ext, out mimeType))
                {
                    return mimeType;
                }
            }
            return null;
        }

        public NameControl()
        {
            InitializeComponent();
        }

        private void _SetUserTile(Stream stm, string originalName)
        {
            var view = (ContactInfo)DataContext;
            Stream disposable = view.UserTile.Value;
            Utility.SafeDispose(ref disposable);
            if (null != stm)
            {
                view.UserTile.Value = stm;
                view.UserTile.ValueType = _TryGetMimeTypeFromExtension(originalName);
            }
            else
            {
                view.UserTile.Clear();
            }
        }

        private void _OnUserTileClick(object source, RoutedEventArgs e)
        {
            var ofn = new OpenFileDialog
            {
                Filter = "All Picture Files|*.BMP;*.GIF;*.JPEG;*.JPG;*.JPE;*.JFIF;*.PNG;*.TIF;*.TIFF;*.ICO|Bitmap Files (*.BMP)|*.BMP|GIF (*.GIF)|*.GIF|JPEG (*.JPEG;*.JPG;*.JPE;*.JFIF)|*.JPEG;*.JPG;*.JPE;*.JFIF|PNG (*.PNG)|*.PNG|TIFF (*.TIF;*.TIFF)|*.TIF;*.TIFF|ICO (*.ICO)|*.ICO|All Files|*",
                Title = "Select User Tile",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                Multiselect = false,
            };

            if (ofn.ShowDialog() == true)
            {
                _SetUserTile(ofn.OpenFile(), ofn.FileName);
            }
        }

        private void _OnUserTileClear(object source, RoutedEventArgs e)
        {
            _SetUserTile(null, null);
        }

        private void _OnUserTileOpen(object sender, RoutedEventArgs e)
        {
            string fileToStart = null;

            var view = (ContactInfo)DataContext;
            if (view.UserTile.Value != null)
            {
                Stream imageStream = view.UserTile.Value;
                string filePath = Path.Combine(Path.GetTempPath(), view.Name.FormattedName ?? "contact") + "." + _TryGetExtensionFromMimeType(view.UserTile.ValueType);
                using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, (int)imageStream.Length))
                {
                    Utility.CopyStream(fs, imageStream);
                    fileToStart = filePath;
                }
            }
            else if (view.UserTile.Url != null)
            {
                fileToStart = view.UserTile.Url.OriginalString;
            }

            Assert.IsNeitherNullNorEmpty(fileToStart);
            if (fileToStart != null)
            {
                System.Diagnostics.Process.Start(fileToStart);
            }
        }
    }
}